package com.breaking.second.utils.okhttp;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.breaking.second.activity.login.LoginActivity;
import com.breaking.second.application.EscortApplication;
import com.breaking.second.entity.AppEntity;
import com.breaking.second.entity.BookEntity;
import com.breaking.second.utils.compat.FormBodyCompat;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class OkhttpUtil {
    private final static String url = "https://api-store.openguet.cn/api/member/tran/";
    private final static AppEntity app = new AppEntity();

    public static void uploadImage(List<File> files, CallbackListener callback) {
        // 创建 MultipartBody
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        // 添加每个文件到 MultipartBody
        for (File file : files) {
            builder.addFormDataPart("fileList", file.getName(),
                    RequestBody.create(file, MediaType.parse("image/jpeg"))); // 根据实际文件类型调整
        }
        // 创建请求
        Request request = new Request.Builder()
                .url(url + "image/upload")
                .post(builder.build())
                .addHeader("appId", app.getAppId())
                .addHeader("appSecret", app.getAppSecret())
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Content-Type", "multipart/form-data")
                .build();
        CallbackX callbackX = new CallbackX(callback);
        // 发送请求
        client().newCall(request).enqueue(callbackX);
    }

    public static void Post(String path, FormBody.Builder formBody, CallbackListener callback, RefreshLayout refreshLayout) {
        CallbackX callbackX = new CallbackX(callback, refreshLayout);
        JSONObject json = formBodyToJson(formBody.build());
        MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
        Request.Builder builder = new Request.Builder()
                .url(url + path)
                .addHeader("appId", app.getAppId())
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("appSecret", app.getAppSecret())
                .post(RequestBody.create(MEDIA_TYPE_JSON, json.toString()));
        client().newCall(builder.build()).enqueue(callbackX);
    }


    public static void Post(String path, FormBody.Builder formBody, CallbackListener callback) {
        CallbackX callbackX = new CallbackX(callback);
        MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
        JSONObject json = formBodyToJson(formBody.build());
        Request.Builder builder = new Request.Builder()
                .url(url + path)
                .addHeader("appId", app.getAppId())
                .addHeader("appSecret", app.getAppSecret())
                .addHeader("Accept", "application/json, text/plain, */*")
                .post(RequestBody.create(MEDIA_TYPE_JSON, json.toString()));
        client().newCall(builder.build()).enqueue(callbackX);
    }

    public static void Post(String path, JSONObject json, CallbackListener callback) {
        CallbackX callbackX = new CallbackX(callback);
        MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
        Request.Builder builder = new Request.Builder()
                .url(url + path)
                .addHeader("appId", app.getAppId())
                .addHeader("appSecret", app.getAppSecret())
                .addHeader("Accept", "application/json, text/plain, */*")
                .post(RequestBody.create(MEDIA_TYPE_JSON, json.toString()));
        client().newCall(builder.build()).enqueue(callbackX);
    }

    public static void Get(String path, CallbackListener callback) {
        CallbackX callbackX = new CallbackX(callback);
        Request.Builder builder = new Request.Builder()
                .url(url + path)
                .addHeader("appId", app.getAppId())
                .addHeader("appSecret", app.getAppSecret())
                .addHeader("Accept", "application/json, text/plain, */*");
        client().newCall(builder.build()).enqueue(callbackX);
    }

    public static void Get(String path, FormBody.Builder form, CallbackListener callback) {
        CallbackX callbackX = new CallbackX(callback);
        String url1 = formBodyToQueryString(url + path, form.build());
        Log.d("數據", url1);
        Request.Builder builder = new Request.Builder()
                .url(formBodyToQueryString(url + path, form.build()))
                .addHeader("appId", app.getAppId())
                .addHeader("appSecret", app.getAppSecret())
                .addHeader("Accept", "application/json, text/plain, */*");
        client().newCall(builder.build()).enqueue(callbackX);
    }


    public static void Get(String path, FormBody.Builder form, CallbackListener callback, RefreshLayout refreshLayout) {
        CallbackX callbackX = new CallbackX(callback, refreshLayout);
        Request.Builder builder = new Request.Builder()
                .url(formBodyToQueryString(url + path, form.build()))
                .addHeader("appId", app.getAppId())
                .addHeader("appSecret", app.getAppSecret())
                .addHeader("Accept", "application/json, text/plain, */*");
        client().newCall(builder.build()).enqueue(callbackX);
    }

    public static String formBodyToQueryString(String url, FormBody formBody) {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        for (int i = 0; i < formBody.size(); i++) {
            String key = formBody.encodedName(i);
            String value = formBody.encodedValue(i);
            urlBuilder.addQueryParameter(key, value);
        }
        return urlBuilder.build().toString();
    }


    public static JSONObject formBodyToJson(FormBody formBody) {
        JSONObject jsonObject = new JSONObject();
        for (int i = 0; i < formBody.size(); i++) {
            String key = formBody.encodedName(i);
            String value = formBody.encodedValue(i);
            jsonObject.put(key, value);
        }
        return jsonObject;
    }

    public static OkHttpClient client() {
        return new OkHttpClient();
    }

    public static class CallbackX implements Callback, Handler.Callback {
        private final CallbackListener callbackListener;
        private final Handler handler = new Handler(Looper.getMainLooper(), this);
        private RefreshLayout refreshLayout;

        public CallbackX(CallbackListener callbackListener) {
            this.callbackListener = callbackListener;
        }

        public CallbackX(CallbackListener callbackListener, RefreshLayout refreshLayout) {
            this.callbackListener = callbackListener;
            this.refreshLayout = refreshLayout;
        }

        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
            if (callbackListener.callbackError == null) return;
            Message message = new Message();
            message.obj = e;
            handler.sendMessageDelayed(message, 0);
        }

        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            if (callbackListener.callbackSuccess == null) return;
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                throw new IOException("响应为空");
            } else {
                String text = responseBody.string();
                Log.d("响应", text);
                BookEntity bookEntity = JSON.parseObject(text, BookEntity.class);
                Message message = new Message();
                message.obj = bookEntity;
                handler.sendMessageDelayed(message, 0);
            }
        }

        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.obj instanceof IOException e) {
                e.printStackTrace();
                if (callbackListener.callbackError == null) {
                    Toast.makeText(EscortApplication.getEscortApplication(), "网络失败", Toast.LENGTH_SHORT).show();
                } else {
                    callbackListener.callbackError.onFailure(e);
                }
                if (refreshLayout == null) {
                    return false;
                }
                refreshLayout.finishRefresh(false);
                refreshLayout.finishLoadMore(false);
            } else if (msg.obj instanceof BookEntity entity) {
                callbackListener.callbackSuccess.onResponse(entity);
                if (refreshLayout == null) {
                    return false;
                }
                refreshLayout.finishLoadMore(0);
                refreshLayout.finishRefresh(0);
            }
            return false;
        }
    }

    public static class CallbackListener {
        private final CallbackSuccess callbackSuccess;
        private final CallbackError callbackError;

        public CallbackListener(CallbackSuccess callbackSuccess, CallbackError callbackError) {
            this.callbackSuccess = callbackSuccess;
            this.callbackError = callbackError;
        }

        public CallbackListener(CallbackSuccess callbackSuccess) {
            this.callbackSuccess = callbackSuccess;
            this.callbackError = null;
        }
    }

    public interface CallbackSuccess {
        void onResponse(BookEntity bookEntity);
    }

    public interface CallbackError {
        void onFailure(IOException e);
    }
}
